package com.yjd.back.merchant;

import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.merchant.model.MerchantCashModel;
import com.yjd.comm.merchant.model.MerchantModel;
import com.yjd.comm.merchant.service.IMerchantCashService;
import com.yjd.comm.merchant.service.IMerchantService;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.util.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 后台商户信息管理
 * Created by yangchangyan on 2017/8/15.
 */
@Controller("com.yjd.back.merchant.MerchantControl")
@Scope("prototype")
@RequestMapping("/merchant")
public class MerchantControl extends BaseControl {

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IMerchantService merchantService;

    @Resource
    private IMerchantCashService merchantCashService;

    /**
     * 商户账号列表
     * Created by yangchangyan on 2017/8/16.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/all")
    public String allMerchant() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("sort", "create_time desc");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.merchantService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/org/all"));

        MerchantModel merchant = null;
        OrganizationModel org = null;
        for(Object obj : pager.getPagerModel().getDataList()){
            merchant = (MerchantModel) obj;
            org = organizationService.getModelById(merchant.getOrg_id(), DbWREnums.READ);
            if(null == org){
                continue;
            }
            merchant.getStrMap().put("org_name", org.getOrg_name());
            merchant.getStrMap().put("last_login_time", DateUtil.timestampToDateString(merchant.getLast_login_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            merchant.getStrMap().put("org_tel_number", org.getOrg_tel_number());
            merchant.getStrMap().put("org_address", CityUtil.getFullCityNames(org.getOrg_city(), "-")+" "+org.getOrg_address());
            merchant.getStrMap().put("create_time", DateUtil.timestampToDateString(merchant.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            merchant.getStrMap().put("last_update_time", DateUtil.timestampToDateString(merchant.getUpdate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);
        return "merchant.list";
    }

    /**
     * 商户账号详情
     * Created by yangchangyan on 2017/8/16.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/info")
    public String merchantInfo(Long id) throws Exception {
        request.setAttribute("detail", organizationService.getModelById(id, DbWREnums.READ));
        return "merchant.detail";
    }

    /**
     * 添加商户账号
     * Created by yangchangyan on 2017/8/16.
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping(value = "/add")
    public String addMerchant(Long id) throws Exception {
        if(null != id){
            request.setAttribute("merchant", this.merchantService.getModelById(id, DbWREnums.READ));
        }
        request.setAttribute("orgids", organizationService.allOrgAndName());
        return "merchant.edit";
    }

    @RequestMapping(value = "/add/submit")
    public void addMerchantSubmit(MerchantModel merchant) throws Exception {
        if (    StringUtil.isEmpty(merchant.getOrg_id()) ||
                StringUtil.isEmpty(merchant.getName()) ||
                StringUtil.isEmpty(merchant.getPassword()) ) {
            FrameUtil.throwBaseException1("信息不完整");
        }

        /**
         * 如果某机构未添加账户，则新增一个，并设置密钥、用户名、密码等信息。
         * 如果某机构已经添加了账户，则更新当前账户，会更新用户名、密码、状态。
         */
        MerchantModel dbMerchant = merchantService.getModelOne(FrameUtil.newHashMap("name", merchant.getName()), DbWREnums.READ);
        Long current = FrameUtil.getTime();
        if(null == dbMerchant){
            merchant.setEncrypt(SecurityCode.getRandomCode(6));
            merchant.setPassword(SecurityCode.passwordMD5_2(merchant.getPassword(), merchant.getEncrypt()));
            merchant.setCreate_time(current);
            merchant.setUpdate_time(current);
            try {
                merchantService.openMerchant(merchant);
            } catch (org.springframework.dao.DuplicateKeyException e){
                FrameUtil.throwBaseException1("此机构的账号已经存在，不能重复创建。");
            }
        } else {
            dbMerchant.setName(merchant.getName());
            dbMerchant.setStatus(merchant.getStatus());
            dbMerchant.setPassword(""); // 更新时，默认不更新密码，如果填了密码，则更新为新密码。
            if(StringUtil.isNotEmpty(merchant.getPassword())){
                dbMerchant.setPassword(SecurityCode.passwordMD5_2(merchant.getPassword(), dbMerchant.getEncrypt()));
            }
            dbMerchant.setUpdate_time(current);
            merchantService.update(dbMerchant);
        }

        this.successMsg(ServletUtil.getUrl("/merchant/all"), "保存账号成功");
    }

    @RequestMapping(value = "/delete")
    public void deleteMerchant(Long id, String name) throws Exception {
        MerchantModel merchant = this.merchantService.getModelOne(FrameUtil.newHashMap("org_id", id, "name", name), DbWREnums.READ);
        if (null == merchant) {
            FrameUtil.throwBaseException1("账户不存在");
        }

        merchantService.deleteMerchantAndFundsAccount(merchant);

        this.successMsg("删除账户成功");
    }

    @RequestMapping(value = "/cash/out/list")
    public String merchantCashoutList() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("sort", "create_time desc");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.merchantCashService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/merchant/cash/out/list"));

        Map<Long, String> orgids = organizationService.allOrgAndName();

        MerchantCashModel cashModel = null;
        OrganizationModel org = null;
        for(Object obj : pager.getPagerModel().getDataList()){
            cashModel = (MerchantCashModel) obj;
            cashModel.getStrMap().put("org_name", orgids.get(cashModel.getOrg_id()));
            cashModel.getStrMap().put("create_time", DateUtil.timestampToDateString(cashModel.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);
        request.setAttribute("orgids", orgids);
        return "merchant.cashout.list";
    }

    @RequestMapping(value = "/cash/out/apply")
    public String merchantCashoutApply() throws Exception {
        request.setAttribute("orgids", organizationService.allOrgAndName());
        return "merchant.cashout";
    }

    @RequestMapping(value = "/cash/out")
    public void merchantCashout(MerchantCashModel cashout) throws Exception {
        if(null == cashout){
            this.errorMsg("信息不完整");
            return;
        }

        merchantCashService.merchantCashOut(cashout);

        this.successMsg(ServletUtil.getUrl("/merchant/cash/out/list"),"保存成功");
    }
}
